import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

/*creacion de los autos, lectura de las vueltas, arranque del hilo*/
@SuppressWarnings("serial")
public class Race extends JFrame {
	JTextField names[], laps;
	JButton start;
	static JProgressBar progress[];
	Container vista;
	GridBagConstraints param;
	GridBagLayout orden;
	int lapsinput;
	static int y=0;
	static String[] aorder = new String[5];
	static String posiciones="";
	
	
	public static void arrived(String n){
		if(y<=4){
		aorder[y]=n;
		posiciones+="\nPosicion "+(y+1)+" :"+aorder[y];
		if(y==4)
			JOptionPane.showMessageDialog(null,"El ganador es: "+aorder[0]+"\n\nTabla de Posiciones"+posiciones);
		y++;
		}
	}

	public Race() {
		super("Carrera de Autos");
		vista = getContentPane();
		orden = new GridBagLayout();
		vista.setLayout(orden);
		param = new GridBagConstraints();

		names = new JTextField[5];
		laps = new JTextField("# de vueltas");
		start = new JButton("Start!");
		progress = new JProgressBar[5];
		
		
		addtogrid(laps, 0, 4, 1, 1);
		addtogrid(start, 0, 5, 1, 1);
		for (int x = 0; x < 5; x++) {
			names[x] = new JTextField("Auto " + (x + 1));
			addtogrid(names[x], x + 1, 0, 1, 1);
			progress[x] = new JProgressBar();
			progress[x].setStringPainted(true);
			progress[x].setString("Inicio");
			addtogrid(progress[x], x + 1, 1, 5, 1);
		}
		inputmanager im = new inputmanager();
		start.addActionListener(im);
		setSize(300,200);
		setVisible(true);
	}

	private void addtogrid(Component componente, int fila, int columna,
			int anchura, int altura) {
		param.gridy = fila;
		param.gridx = columna;
		param.gridwidth = anchura;
		param.gridheight = altura;
		param.fill=GridBagConstraints.BOTH;
		orden.setConstraints(componente, param);
		vista.add(componente);
	}

	public static void main(String[] args) {
		Race app = new Race();
		app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public class inputmanager implements ActionListener {

		public void actionPerformed(ActionEvent ae) {
			if (ae.getSource() == start) {
				try{
				lapsinput=Integer.parseInt(laps.getText());
				for (int x = 0; x < 5; x++) {
					progress[x].setMinimum(0);
					progress[x].setMaximum(lapsinput);
					progress[x].setString("Inicio");
				}
				
				RaceCar[] cars = new RaceCar[5];

				for (int x = 0; x < 5; x++) {
					cars[x] = new RaceCar(lapsinput, x,
							names[x].getText());
				}
				for (int x = 0; x < 5; x++) {
					cars[x].start();
				}
				}catch(Exception e){
					JOptionPane.showMessageDialog(null,"Introduzca un numero de vueltas valido!");
				}				

			}
		}
	}
}


